<template>
  <s-clean-layout title="账目类型" navbar="normal">
    <view class="type-selector-container">
      <!-- 添加人情类型按钮 -->
      <view class="add-type-btn" @tap="showAddTypeDialog">
        <text class="add-type-text">添加人情类型</text>
      </view>

      <!-- 类型列表 -->
      <view class="type-list">
        <view
          v-for="(item, index) in typeList"
          :key="index"
          class="type-item"
          @tap="selectType(item.name)"
        >
          <text class="type-name">{{ item.name }}</text>
          <uni-icons v-if="selectedType === item.name" type="checkmarkempty" size="20" color="#007AFF"></uni-icons>
          <view class="delete-icon" v-if="isEditMode" @tap.stop="deleteType(index)">
            <uni-icons type="closeempty" size="16" color="#E57373"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
      <view style="height: 120rpx;"></view>
      
      <!-- 底部保存按钮 -->
      <view class="bottom-save-button" @tap="toggleEditMode">
        <text>{{ isEditMode ? '完成' : '编辑' }}</text>
      </view>

      <!-- 添加类型弹窗 -->
      <view class="popup-mask" v-if="showPopup" @tap="closeAddTypeDialog">
        <view class="popup-content-wrapper" @tap.stop>
          <view class="popup-header">
            <text class="popup-cancel" @tap="closeAddTypeDialog">取消</text>
            <text class="popup-title">添加类型</text>
            <text class="popup-confirm" @tap="confirmAddType">完成</text>
          </view>
          <view class="popup-content">
            <input
              class="type-input"
              v-model="newTypeName"
              placeholder="请输入"
              maxlength="10"
              focus
            />
          </view>
          <view class="popup-footer">
            <button class="confirm-btn" @tap="confirmAddType">完成</button>
          </view>
        </view>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
// Import the uni-popup component
import { ref, onMounted, computed } from 'vue';
import CommApi from '@/sheep/api/comm/comm';

// 选中的类型
const selectedType = ref('');
// 类型列表
const typeList = ref([]);
// 新类型名称
const newTypeName = ref('');
// 弹窗显示状态
const showPopup = ref(false);
// 编辑模式
const isEditMode = ref(false);

// 获取人情类型列表
const getAccountTypeList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const res = await CommApi.queryUserBusinCategory({
      businType: 'HUMAN_TRANSACTION'
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      typeList.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName
      }));
    } else {
      uni.showToast({
        title: '获取人情类型失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取人情类型列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 选择类型
const selectType = (type) => {
  selectedType.value = type;
  
  // 查找选中类型的完整信息
  const selectedTypeInfo = typeList.value.find(item => item.name === type);
  if (!selectedTypeInfo) return;
  
  // 直接返回并传值
  uni.setStorageSync('selectedAccountType', {
    id: selectedTypeInfo.id,
    name: selectedTypeInfo.name
  });
  uni.$emit('updateAccountType', { 
    type: {
      id: selectedTypeInfo.id,
      name: selectedTypeInfo.name
    }
  });
  uni.navigateBack();
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示添加类型弹窗
const showAddTypeDialog = () => {
  newTypeName.value = '';
  showPopup.value = true;
};

// 关闭添加类型弹窗
const closeAddTypeDialog = () => {
  showPopup.value = false;
};

// 删除类型
const deleteType = async (index) => {
  const typeId = typeList.value[index].id;
  
  try {
    uni.showLoading({
      title: '删除中...'
    });
    
    const res = await CommApi.deleteUserBusinCategory({
      id: typeId,
      businType: 'HUMAN_TRANSACTION'
    });
    
    uni.hideLoading();
    
    if (res.code === 0) {
      typeList.value.splice(index, 1);
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('删除人情类型失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 确认添加类型
const confirmAddType = async () => {
  if (newTypeName.value.trim()) {
    // 检查是否已存在于类型列表中
    if (!typeList.value.some(item => item.name === newTypeName.value.trim())) {
      try {
        uni.showLoading({
          title: '添加中...'
        });
        
        const res = await CommApi.addUserBusinCategory({
          categoryName: newTypeName.value.trim(),
          businType: 'HUMAN_TRANSACTION',
          sortOrder: 0
        });
        
        uni.hideLoading();
        
        if (res.code === 0) {
          // 添加到本地列表
          typeList.value.push({
            id: res.data,
            name: newTypeName.value.trim()
          });
          
          // 关闭弹窗
          closeAddTypeDialog();
          
          // 自动选中新添加的类型
          selectedType.value = newTypeName.value.trim();
          
          // 可选：直接返回并传值
          uni.setStorageSync('selectedAccountType', {
            id: res.data,
            name: newTypeName.value.trim()
          });
          uni.$emit('updateAccountType', { type: newTypeName.value.trim() });
          uni.navigateBack();
          
          uni.showToast({
            title: '添加成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '添加失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('添加人情类型失败:', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: '该类型已存在',
        icon: 'none'
      });
    }
  } else {
    uni.showToast({
      title: '类型名称不能为空',
      icon: 'none'
    });
  }
};

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
};

onMounted(() => {
  // 从本地存储加载自定义类型
  getAccountTypeList();
  
  // 获取URL参数中的当前选中类型
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options && options.defaultType) {
    selectedType.value = decodeURIComponent(options.defaultType);
  }
  
  // 尝试获取事件通道传递的类型
  try {
    const eventChannel = currentPage.$getOpenerEventChannel && currentPage.$getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.on('getCurrentType', (data) => {
        if (data && data.currentType) {
          selectedType.value = data.currentType;
        }
      });
    }
  } catch (e) {
    console.error('获取事件通道失败:', e);
  }
});
</script>

<style lang="scss" scoped>
.type-selector-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-top: 20rpx;
}

/* 移除原有的header样式 */
.header {
  display: none;
}

/* 底部保存按钮样式 */
.bottom-save-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #2196F3;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  border-radius: 45rpx;
  margin-bottom: env(safe-area-inset-bottom);
}

.add-type-btn {
  margin: 30rpx;
  height: 88rpx;
  background-color: #fff;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-type-text {
  color: #007AFF;
  font-size: 32rpx;
}

.type-list {
  background-color: #fff;
  margin: 0 30rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.type-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.type-name {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.delete-icon {
  position: absolute;
  right: 60rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

.type-input {
  height: 80rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-top: 20rpx;
  font-size: 28rpx;
}

.custom-popup {
  width: 80vw;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

// 弹窗样式
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-content-wrapper {
  width: 90%;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-cancel {
  color: #333;
  font-size: 32rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.popup-confirm {
  color: #007AFF;
  font-size: 32rpx;
}

.popup-content {
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.type-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 32rpx;
  text-align: center;
}

.emoji-container {
  width: 120rpx;
  height: 120rpx;
  background-color: #f5f5f5;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 50rpx;
}

.emoji-image {
  width: 80%;
  height: 80%;
}

.popup-footer {
  padding: 20rpx 30rpx 40rpx;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background-color: #007AFF;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  border: none;
}
</style>